package com.whiteape.book.ui.fragment;

import android.os.Bundle;
import android.view.View;
import android.widget.EditText;

import androidx.appcompat.app.AlertDialog;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.hwangjr.rxbus.RxBus;
import com.hwangjr.rxbus.annotation.Subscribe;
import com.hwangjr.rxbus.annotation.Tag;
import com.hwangjr.rxbus.thread.EventThread;
import com.whiteape.book.R;
import com.whiteape.book.common.RxEvent;
import com.whiteape.book.contract.MediaCollectionContract;
import com.whiteape.book.core.manager.MediaStorageManager;
import com.whiteape.book.model.dto.CollectionMediaBean;
import com.whiteape.book.model.dto.CollectionMediaGroupBean;
import com.whiteape.book.model.type.MediaType;
import com.whiteape.book.model.type.RVLayoutType;
import com.whiteape.book.presenter.MediaCollectionPresenter;
import com.whiteape.book.ui.activity.BookReadActivity;
import com.whiteape.book.ui.activity.ComicReadActivity;
import com.whiteape.book.ui.adapter.MediaCollectionGroupAdapter;
import com.whiteape.book.ui.base.BaseRVMVPFragment;
import com.whiteape.book.utils.RxUtils;
import com.whiteape.book.utils.StringUtils;
import com.whiteape.book.utils.ToastUtils;
import com.whiteape.book.widget.RefreshLayout;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import butterknife.BindView;
import io.reactivex.disposables.Disposable;

public class MediaGroupDetailFragment extends BaseRVMVPFragment<MediaCollectionContract.Presenter, CollectionMediaBean>
        implements MediaCollectionContract.View {

    MediaCollectionGroupAdapter mListAdapter;
    MediaCollectionGroupAdapter mGridAdapter;

    private List<CollectionMediaBean> mData = new ArrayList<>();

    @BindView(R.id.refresh_layout_loading)
    RefreshLayout refreshLayout;

    private static final String KEY_MEDIA_TYPE = "media_type";
    private static final String KEY_DATA = "media_data";
    private int mediaType = MediaType.MEDIA_TYPE_NOVEL;

    public static MediaGroupDetailFragment newInstance(int mediaType, ArrayList<CollectionMediaBean> data) {
        Bundle args = new Bundle();
        args.putInt(KEY_MEDIA_TYPE, mediaType);
        args.putParcelableArrayList(KEY_DATA, data);
        MediaGroupDetailFragment fragment = new MediaGroupDetailFragment();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    protected boolean setBatchDeleteEnabled() {
        return true;
    }

    @Override
    protected boolean setAdapterModeSwitchEnabled() {
        return true;
    }

    @Override
    protected boolean setMoveEnabled() {
        return true;
    }

    @Override
    protected boolean showTotal() {
        return true;
    }

    @Override
    protected boolean initListOrGrid() {
        //TODO 当前数据是list/grid从 prefs中获取
        return true;
    }

    @Override
    protected boolean setMoveOutEnabled() {
        return true;
    }

    @Override
    protected List<BaseQuickAdapter<CollectionMediaBean, BaseViewHolder>> setAdapter() {
        //TODO
        mListAdapter = new MediaCollectionGroupAdapter(R.layout.item_collection_media_list, mData);
        mGridAdapter = new MediaCollectionGroupAdapter(R.layout.item_collection_media_grid, mData);

        mListAdapter.setLayoutType(RVLayoutType.LIST);
        mGridAdapter.setLayoutType(RVLayoutType.GRID);

        mListAdapter.setSelectedList(mSelectedList);
        mGridAdapter.setSelectedList(mSelectedList);

        List<BaseQuickAdapter<CollectionMediaBean, BaseViewHolder>> adapterList = new ArrayList<>();
        adapterList.add(mListAdapter);
        adapterList.add(mGridAdapter);

        return adapterList;
    }

    @Override
    protected void deleteItems(List<CollectionMediaBean> itemList) {
        List<CollectionMediaBean> beanList = new ArrayList<>(itemList);
        new AlertDialog.Builder(getContext())
                .setTitle(R.string.wa_common_tip)
                .setMessage(getString(R.string.delete_media_msg, itemList.size()))
                .setPositiveButton(R.string.wa_common_sure, (dialog, which) -> {

                    addDisposable(MediaStorageManager.getInstance().deleteCollMediaListInRx(beanList)
                            .compose(RxUtils::toSimpleSingle).subscribe(v -> {
                                mData.removeAll(itemList);
                                mListAdapter.notifyDataSetChanged();
                                mGridAdapter.notifyDataSetChanged();
                                mSelectedList.clear();
                                refresh();
                                RxBus.get().post(RxEvent.MEDIA_COLLECTION_REFRESH, new CollectionMediaBean());
                            }));
                })
                .setNegativeButton(R.string.wa_common_cancel, ((dialog, which) -> {
                    dialog.dismiss();

                })).show();
    }

    @Override
    protected void onItemChildClickListener(BaseQuickAdapter adapter, View view, int position) {

    }

    @Override
    protected void onItemClickListener(BaseQuickAdapter adapter, View view, int position) {

        if (mediaType == MediaType.MEDIA_TYPE_NOVEL) {
            BookReadActivity.startActivity(getContext(), mData.get(position), true, -1);
        } else if (mediaType == MediaType.MEDIA_TYPE_COMIC) {
            ComicReadActivity.startActivity(getContext(), mData.get(position), null, true, null);
        }
    }

    @Override
    protected void onSelectStateChanged(boolean selectStateEnable) {
        mListAdapter.setSelectedStateEnable(selectStateEnable);
        mGridAdapter.setSelectedStateEnable(selectStateEnable);

    }

    @Override
    protected void moveItems(List<CollectionMediaBean> itemList) {
        super.moveItems(itemList);
        List<CollectionMediaGroupBean> groups = MediaStorageManager.getInstance().getMediaGroupList();
        int groupNum = groups.size();
        String[] groupNameArr = new String[groupNum + 1];
        Set<String> groupNameSet = new HashSet<>();
        for (int i = 0; i < groupNum; i++) {
            groupNameArr[i] = groups.get(i).getName();
            groupNameSet.add(groups.get(i).getName());
        }
        groupNameArr[groupNum] = " + 添加分组";
        //移动分组
        new AlertDialog.Builder(getContext())
                .setTitle(R.string.wa_common_move_to_group)
                .setItems(groupNameArr, ((dialog, which) -> {
                    if (which == groupNum) {
                        //最后一个是 添加分组
                        final View view = getLayoutInflater().inflate(R.layout.view_alert_dialog_edittext, null);
                        final EditText editText = (EditText) view.findViewById(R.id.editText);
                        new AlertDialog.Builder(getContext())
                                .setTitle(R.string.wa_common_new_group)
                                .setView(view)
                                .setPositiveButton(R.string.wa_common_sure, (dialog1, which1) -> {
                                    String name = editText.getText().toString();
                                    if (StringUtils.isEmpty(name)) {
                                        ToastUtils.show("分组名字不可为空!");
                                        return;
                                    }
                                    if (groupNameSet.contains(name.trim())) {
                                        ToastUtils.show("该分组已存在！");
                                        return;
                                    }
                                    MediaStorageManager.getInstance().saveMediaGroup(name);
                                    dialog1.dismiss();
                                    moveItems(itemList);

                                })
                                .setNegativeButton(R.string.wa_common_cancel, ((dialog1, which1) -> {
                                    dialog1.dismiss();

                                })).show();
                    } else {
                        List<CollectionMediaBean> beanList = new ArrayList<>();
                        for (CollectionMediaBean bean : itemList) {
                            bean.setGroup(groupNameArr[which]);
                            beanList.add(bean);
                        }
                        mData.removeAll(beanList);
                        mSelectedList.clear();
                        refresh();
                        MediaStorageManager.getInstance().batchSaveCollectionMediaBaseInfo(beanList);
                        RxBus.get().post(RxEvent.MEDIA_COLLECTION_REFRESH, new CollectionMediaBean());
                    }

                })).show();


    }

    @Override
    protected void moveItemsOut(List<CollectionMediaBean> itemList) {
        super.moveItemsOut(itemList);
        new AlertDialog.Builder(getContext()).setTitle("温馨提示")
                .setMessage("确定移出该分组（不会删除）吗？")
                .setPositiveButton("确定", (dialog, which) -> {
                    List<CollectionMediaBean> beanList = new ArrayList<>();
                    for (CollectionMediaBean bean : itemList) {
                        bean.setGroup(null);
                        beanList.add(bean);
                    }
                    mData.removeAll(beanList);
                    mSelectedList.clear();
                    refresh();
                    MediaStorageManager.getInstance().batchSaveCollectionMediaBaseInfo(beanList);
                    RxBus.get().post(RxEvent.MEDIA_COLLECTION_REFRESH, new CollectionMediaBean());
                })
                .setNegativeButton("取消", (dialog, which) -> {
                    dialog.cancel();
                })
                .show();
    }

    @Override
    protected void initData(Bundle savedInstanceState) {
        if (getArguments() != null) {
            mediaType = getArguments().getInt(KEY_MEDIA_TYPE);
            mData = getArguments().getParcelableArrayList(KEY_DATA);
        }
        super.initData(savedInstanceState);
    }

    @Override
    protected MediaCollectionContract.Presenter bindPresenter() {
        return new MediaCollectionPresenter();
    }

    @Override
    protected void startLogic() {
        super.startLogic();
        refreshLayout.showFinish();
        refresh();
    }

    @Override
    public void finishRefresh(List<CollectionMediaBean> collectionMediaBeans, boolean forceRefreshCatalog) {

    }

    @Override
    public void showError() {

    }

    @Override
    public void complete() {

    }

    private void refreshCollectionMediaBean(){
        String groupName = mData.get(0).getGroup();
        Disposable disposable =
                MediaStorageManager.getInstance().getCollectionMediaListByGroupInRx(mediaType, groupName)
                        .compose(RxUtils::toSimpleSingle)
                        .subscribe(beans -> {
                            mData.clear();
                            mData.addAll(beans);
                            refresh();
                        }, Throwable::printStackTrace);
        addDisposable(disposable);
    }

    @Subscribe(thread = EventThread.MAIN_THREAD,
            tags = {@Tag(RxEvent.MEDIA_COLLECTION_ADD),
                    @Tag(RxEvent.MEDIA_COLLECTION_REMOVE),
                    @Tag(RxEvent.MEDIA_COLLECTION_REFRESH)})
    public void onCollectionStateChanged(CollectionMediaBean collectionMediaBean) {
        refreshCollectionMediaBean();
    }
}
